package example.recursive.wordcounter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by IntelliJ IDEA.
 * User: Chen Yi
 * Date: 11-5-28
 */
public class FutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        File startDirectory = new File("src");
        String keyWord = "List";

        MatchCounter matchCounter = new MatchCounter(startDirectory, keyWord);
        FutureTask<Integer> futureTask = new FutureTask<Integer>(matchCounter);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }
    
    static class MatchCounter implements Callable<Integer>{
        int count;
        private String keyWord;
        private File startDirectory;

        public MatchCounter(File startDirectory, String keyWord) {
            this.startDirectory = startDirectory;
            this.keyWord = keyWord;
        }

        public Integer call() throws Exception {
            count = 0;
            File[] files = startDirectory.listFiles();
            List<FutureTask<Integer>> results = new ArrayList<FutureTask<Integer>>();
            for (File file : files) {
                if(file.isDirectory()){
                    MatchCounter matchCounter = new MatchCounter(file, keyWord);
                    FutureTask<Integer> futureTask = new FutureTask<Integer>(matchCounter);
                    results.add(futureTask);
                    new Thread(futureTask).start();
                }else {
                    if(search(file, keyWord)){
                        count++;
                    }
                }
            }
            for (FutureTask<Integer> result : results) {
                count += result.get();
            }

            return count;
        }

        private boolean search(File file, String keyWord) throws FileNotFoundException {
            Scanner scanner = new Scanner(file);
            boolean isMatched = false;
            while (!isMatched && scanner.hasNextLine()){
                String line = scanner.nextLine();
                if(line.contains(keyWord)){
                    System.out.println(file.getName() + ": " + line);
                    isMatched = true;
                }
            }
            return isMatched;
        }
    }

}